package com.example.hrm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.hrm.entity.Employees;
import com.example.hrm.entity.UserAuthentication;
import com.example.hrm.service.EmployeesService;
import com.example.hrm.service.UserAuthenticationService;
import com.example.hrm.mapper.UserAuthenticationMapper;
import com.example.hrm.util.JwtTokenProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
* @author DELL
* @description 针对表【user_authentication】的数据库操作Service实现
* @createDate 2025-08-02 14:48:13
*/
@Service
public class UserAuthenticationServiceImpl extends ServiceImpl<UserAuthenticationMapper, UserAuthentication>
    implements UserAuthenticationService{

    // 移除PasswordEncoder的自动注入
    // @Autowired
    // private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenProvider jwtTokenProvider;
    @Autowired
    private EmployeesService employeesService;

    @Override
    public Map<String, String> login(String username, String password) {
        UserAuthentication user = getOne(new LambdaQueryWrapper<UserAuthentication>()
                .eq(UserAuthentication::getUsername,username));
        if (user==null||!password.equals(user.getPassword())) {  // 直接比较明文密码
            throw new RuntimeException("用户名或密码错误");
        }
        user.setLastLogin(new Date());
        updateById(user);
        String token = jwtTokenProvider.generateToken(username,user.getRole().toString());
        Map<String,String> response = new HashMap<>();
        response.put("token",token);
        response.put("role",user.getRole().toString());
        // 添加用户信息
        response.put("username", user.getUsername());
        response.put("userId", user.getAuthId().toString());
        return response;
    }

    @Override
    public void register(String username, String password, String email, String phone) {
        if (existsByUsername(username)){
            throw new RuntimeException("用户名已存在");
        }
        
        // 先创建员工记录
        Employees newEmployee = new Employees();
        newEmployee.setEmployeeNo("EMP" + System.currentTimeMillis()); // 生成简单的员工编号
        newEmployee.setName(username); // 使用用户名为员工姓名
        newEmployee.setGender("其他");
        newEmployee.setBirthDate(new Date());
        newEmployee.setPhone(phone);
        newEmployee.setEmail(email);
        newEmployee.setDepartment("未分配");
        newEmployee.setPosition("员工");
        newEmployee.setHireDate(new Date());
        newEmployee.setAvatarUrl("https://picsum.photos/200/200?random=1");
        newEmployee.setStatus("在职");
        newEmployee.setCreatedAt(new Date());
        newEmployee.setUpdatedAt(new Date());
        
        employeesService.save(newEmployee);
        
        // 再创建用户认证记录
        UserAuthentication newUser = new UserAuthentication();
        newUser.setEmployeeId(newEmployee.getEmployeeId()); // 设置外键
        newUser.setUsername(username);
        newUser.setPassword(password);  // 存储明文密码
        newUser.setRole("admin");
        newUser.setStatus("启用");
        newUser.setCreatedAt(new Date());
        newUser.setUpdatedAt(new Date());
        save(newUser);
    }

    @Override
    public boolean existsByUsername(String username) {
        return count(new LambdaQueryWrapper<UserAuthentication>().eq(UserAuthentication::getUsername,username))>0;
    }

    // 添加一个方法来重置密码为BCrypt格式
    // 修改重置密码方法，不加密
    public void resetPassword(String username, String newPassword) {
        if (username == null || username.isEmpty()) {
            throw new RuntimeException("用户名不能为空");
        }
        if (newPassword == null || newPassword.isEmpty()) {
            throw new RuntimeException("新密码不能为空");
        }

        UserAuthentication user = getOne(new LambdaQueryWrapper<UserAuthentication>()
                .eq(UserAuthentication::getUsername, username));

        if (user == null) {
            throw new RuntimeException("用户不存在: " + username);
        }

        try {
            user.setPassword(newPassword);  // 存储明文密码
            boolean updated = updateById(user);
            if (!updated) {
                throw new RuntimeException("更新密码失败，数据库操作未成功");
            }
        } catch (Exception e) {
            throw new RuntimeException("重置密码时发生错误: " + (e.getMessage() != null ? e.getMessage() : "未知错误"), e);
        }
    }

    @Override
    public void logout(String token) {
        jwtTokenProvider.validateToken(token);
    }


}




